package ai.zixing.singleton;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 序列化对单例的破环
 */
public class Test_Serializable {

    public static void main(String[] args) throws Exception{
        // 序列化对象输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("temp.obj"));
        oos.writeObject(Singleton.getInstance());
        // 序列化对象输入流
        File file = new File("temp.obj");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        Singleton singleton = (Singleton) ois.readObject();

        System.out.println(singleton);
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance() == singleton);
    }

}

/**
 * 实现序列化的单例对象
 */
class Singleton implements Serializable {
    private Singleton() {
    }

    private static volatile Singleton instance;

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    /**
     * 解决方法:只需要子啊单例类中定义 readResolve() 方法，就可以解决序列化对单例的破坏
     * @return
     */
    private Object readResolve() {
        return instance;
    }
}
